/*
<div id="app">你好{{name}}</div>
render(){
    return _c('div',{id:'app',_v('你好'+_s(name)),_c})
}
*/
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g; //匹配{{xxx}}
// 处理属性
function genProps(attrs) {

    let str = '';
    // 遍历每一个属性对象
    for (let i = 0; i < attrs.length; i++) {
      let attr = attrs[i]
        //   如果是style属性的话
      if(attr.name === 'style'){
        let obj = {}
        attr.value.split(';').forEach(item => {
            let [key,val] = item.split(':')
            
            obj[key] = val
        });
       attr.value = obj
      }
      str+=`${attr.name}:${JSON.stringify(attr.value)},`
    }
    return `{${str.slice(0,-1)}}`
}

// 处理子节点
function genChildren(el) {
    
    let children = el.children
    
    if(children){
    //    console.log(children.map(child=>gen(child)).join(','));
        return children.map(child=>gen(child)).join(',')
    } 
}
function gen(node) {
    if(node.type===1){ // 是元素
        return generate(node)
    } else {
        let text = node.text
        // 没有差值表达式的
        if(!defaultTagRE.test(text)){
            return `_v(${JSON.stringify(text)})`
        }
        // 带有{{}}  
        // 处理插值表达式
        let tokens = []
        let lastindex = defaultTagRE.lastIndex = 0
        let match
        while (match = defaultTagRE.exec(text)) {
           let index = match.index
           if(index>lastindex){ //添加内容
            tokens.push(JSON.stringify(text.slice(lastindex,index)))
           }
           tokens.push(`_s(${match[1].trim()})`)
           lastindex = index + match[0].length
        }
        if(lastindex<text.length){
            tokens.push(JSON.stringify(text.slice(lastindex)))
        }
        return `_v(${tokens.join('+')})`
    }
}

export function generate(el) {
    let children = genChildren(el)
    let code = `_c('${el.tag}',${el.attrs.length?`${genProps(el.attrs)}`:'undefined'}${children?`,${children}`:''})`
    // console.log(code);
    
    return code
}